package org.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.example.mapper.SetmealBasicMapper;
import org.example.model.common.dtos.PageResponseDto;
import org.example.model.common.dtos.dish.DishBasicDto;
import org.example.model.common.dtos.setmeal.DishAndNumDto;
import org.example.model.common.dtos.setmeal.SetmealBasicDto;
import org.example.model.common.vos.setmeal.SearchSetmealVo;
import org.example.model.setmeal.SetmealBasic;
import org.example.model.setmeal.SetmealDish;
import org.example.service.DishBasicService;
import org.example.service.SetmealBasicService;
import org.example.service.SetmealDishService;
import org.example.service.UserBasicService;
import org.example.utils.PageUtils;
import org.example.utils.UserIdThreadLocalUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 套餐管理
 */
@Service
@Slf4j
@Transactional
public class SetmealBasicServiceImpl extends ServiceImpl<SetmealBasicMapper, SetmealBasic> implements SetmealBasicService {

    @Autowired
    private SetmealBasicMapper setmealBasicMapper;

    @Autowired
    private UserBasicService userBasicService;

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private DishBasicService dishBasicService;

    /**
     * 新增套餐
     *
     * @param setmealBasic
     */
    @Override
    public Boolean InsertSetmealBasic(SetmealBasic setmealBasic) {
        if (setmealBasic == null) return false;
        //获取Token中的数据
        Integer userId = UserIdThreadLocalUtils.getUser();
        if (userId <= 0) return false;
        setmealBasic.setStatus(1);
        setmealBasic.setCreateUser(userId);
        setmealBasic.setCreateDate(LocalDateTime.now());
        setmealBasic.setUpdateUser(userId);
        setmealBasic.setUpdateDate(LocalDateTime.now());
        setmealBasic.setIsDeleted(false);
        //插入套餐基本数据并返回自增主键
        setmealBasicMapper.insert(setmealBasic);
        int setmealId = setmealBasic.getId();
        List<SetmealDish> setmealDishes = setmealBasic.getSetmealDishes();
        //添加菜品套餐关系
        if (setmealDishes != null) {
            for (SetmealDish setmealDish : setmealDishes) {
                Boolean flag = setmealDishService.InsertSetmealDish(setmealDish,setmealId);
                if (!flag) return false;
            }
        }
        return setmealId > 0;
    }

    /**
     * 根据id查询套餐详情
     *
     * @param id
     */
    @Override
    public SetmealBasicDto SelectSetmealById(int id) {
        if (id <= 0) return new SetmealBasicDto();
        SetmealBasic setmealBasic = setmealBasicMapper.selectById(id);
        if (setmealBasic == null) return new SetmealBasicDto();
        int createId = setmealBasic.getCreateUser();
        int updateId = setmealBasic.getUpdateUser();
        SetmealBasicDto setmealBasicDto = new SetmealBasicDto();
        BeanUtils.copyProperties(setmealBasic,setmealBasicDto);
        setmealBasicDto.setCreateUser(userBasicService.SelectUserById(createId).getUsername());
        setmealBasicDto.setUpdateUser(userBasicService.SelectUserById(updateId).getUsername());
        List<SetmealDish> setmealDishes = setmealDishService.SelectSetmealDishBySetmealId(id);
        if (setmealDishes == null) return setmealBasicDto;
        List<DishAndNumDto> dishAndNumDtos = new ArrayList<>();
        DishAndNumDto dishAndNumDto = null;
        for (SetmealDish setmealDish : setmealDishes) {
            DishBasicDto dishBasicDto = dishBasicService.SelectDishById(setmealDish.getDishId());
            dishAndNumDto = new DishAndNumDto();
            BeanUtils.copyProperties(dishBasicDto,dishAndNumDto);
            dishAndNumDto.setDishNum(setmealDish.getDishNum());
            dishAndNumDtos.add(dishAndNumDto);
        }
        setmealBasicDto.setDishAndNumDtos(dishAndNumDtos);
        return setmealBasicDto;
    }

    /**
     * 根据条件(套餐名称模糊查询，套餐状态精确查询，套餐分类精确查询)分页查询根据id查询套餐详情
     *
     * @param searchSetmealVo
     * @param pageIndex
     * @param pageSize
     */
    @Override
    public PageResponseDto<List<SetmealBasicDto>> SelectPageByConditions(SearchSetmealVo searchSetmealVo, int pageIndex, int pageSize) {
        LambdaQueryWrapper<SetmealBasic> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealBasic::isIsDeleted,false)
                .like(StringUtils.isNotBlank(searchSetmealVo.getSetmealName()),SetmealBasic::getSetmealName,searchSetmealVo.getSetmealName())
                .eq(searchSetmealVo.getStatus() != 0,SetmealBasic::getStatus,searchSetmealVo.getStatus())
                .eq(searchSetmealVo.getCategoryId() != 0,SetmealBasic::getCategoryId,searchSetmealVo.getCategoryId())
                .orderByDesc(SetmealBasic::getSort)
                .orderByDesc(SetmealBasic::getCreateDate);
        List<SetmealBasic> setmealBasics = setmealBasicMapper.selectList(queryWrapper);
        if (setmealBasics.size() == 0) return new PageResponseDto<>();
        List<SetmealBasicDto> setmealBasicDtos = new ArrayList<>();
        SetmealBasicDto setmealBasicDto = null;
        for (int i = 0; i < setmealBasics.size(); i++) {
            setmealBasicDto = new SetmealBasicDto();
            BeanUtils.copyProperties(setmealBasics.get(i),setmealBasicDto);
            setmealBasicDtos.add(setmealBasicDto);
        }
        setmealBasicDtos =  setmealBasicDtos.stream().map(item -> {
            item = this.SelectSetmealById(item.getId());
            return item;
        }).collect(Collectors.toList());
        PageResponseDto<List<SetmealBasicDto>> pageResponseDto = new PageResponseDto<>();
        pageResponseDto.setSize(setmealBasicDtos.size());
        pageResponseDto.setData(new PageUtils<SetmealBasicDto>().page(setmealBasicDtos,pageIndex,pageSize));
        return pageResponseDto;
    }

    /**
     * 根据id修改菜品
     *
     * @param setmealBasic
     */
    @Override
    public Boolean UpdateSetmealBasicById(SetmealBasic setmealBasic) {
        if (setmealBasic == null) return false;
        SetmealBasic setmeal = setmealBasicMapper.selectById(setmealBasic.getId());
        if (setmeal == null) return false;
        //获取Token中的数据
        Integer userId = UserIdThreadLocalUtils.getUser();
        if (userId <= 0) return false;
        setmealBasic.setCreateUser(setmeal.getCreateUser());
        setmealBasic.setCreateDate(setmeal.getCreateDate());
        setmealBasic.setUpdateUser(userId);
        setmealBasic.setUpdateDate(LocalDateTime.now());
        //清空套餐菜品关系
        setmealDishService.DeleteSetmealDishBySetmealId(setmealBasic.getId());
        //重新添加套餐菜品关系
        if (setmealBasic.getSetmealDishes() != null) {
            for (SetmealDish setmealDish : setmealBasic.getSetmealDishes()) {
                Boolean flag = setmealDishService.InsertSetmealDish(setmealDish,setmealBasic.getId());
                if (!flag) return false;
            }
        }
        return setmealBasicMapper.updateById(setmealBasic) > 0;
    }

    /**
     * 根据id删除套餐信息
     *
     * @param id
     */
    @Override
    public Boolean DeleteSetmealBasicById(int id) {
        if (id <= 0) return false;
        SetmealBasic setmealBasic = setmealBasicMapper.selectById(id);
        if (setmealBasic == null) return false;
        setmealBasic.setIsDeleted(true);
        setmealDishService.DeleteSetmealDishBySetmealId(id);
        return this.UpdateSetmealBasicById(setmealBasic);
    }

    /**
     * 根据id修改套餐状态
     *
     * @param id
     */
    @Override
    public Boolean UpdateSetmealStatusById(int id) {
        if (id <= 0) return false;
        SetmealBasic setmealBasic = setmealBasicMapper.selectById(id);
        if (setmealBasic == null) return false;
        //获取Token中的数据
        Integer userId = UserIdThreadLocalUtils.getUser();
        if (userId <= 0) return false;
        setmealBasic.setStatus(setmealBasic.getStatus() == 1 ? 2 : 1);
        setmealBasic.setUpdateUser(userId);
        setmealBasic.setUpdateDate(LocalDateTime.now());
        return setmealBasicMapper.updateById(setmealBasic) > 0;
    }

    /**
     * 批量修改套餐状态
     *
     * @param ids
     * @param type
     */
    @Override
    public Boolean UpdateSetmealStatusByIds(int[] ids, int type) {
        if (ids == null || ids.length <= 0) return false;
        //获取Token中的数据
        Integer userId = UserIdThreadLocalUtils.getUser();
        if (userId <= 0) return false;
        for (int id : ids) {
            SetmealBasic setmealBasic = setmealBasicMapper.selectById(id);
            setmealBasic.setStatus(type);
            setmealBasic.setUpdateUser(userId);
            setmealBasic.setUpdateDate(LocalDateTime.now());
            Boolean flag =  setmealBasicMapper.updateById(setmealBasic) > 0;
            if (!flag) return false;
        }
        return true;
    }

    /**
     * 批量删除套餐
     *
     * @param ids
     */
    @Override
    public Boolean DeleteSetmealBasicByIds(int[] ids) {
        if (ids == null || ids.length <= 0) return false;
        for (int id : ids) {
            Boolean flag = this.DeleteSetmealBasicById(id);
            if (!flag) return false;
        }
        return true;
    }
}
